//首先实现一个带有阻塞功能的队列
class MyBlockingQueue{
    //这个队列是存放整数元素的
    int[] elems=null;
    //头结点
    int head=0;
    int tail=0;
    int size=0;
    //构造方法
    public MyBlockingQueue(int capacity){
        elems=new int[capacity];
    }
    void put(int elem) throws InterruptedException {
        synchronized(this) {
            if (size >= elems.length) {
                //就要进行阻塞等待
                this.wait();
                return;


            }
            elems[tail] = elem;
            tail++;
            if (tail >= elems.length) {
                tail = 0;
            }
            size++;
           this.notify();

        }
    }
    int take() throws InterruptedException {
        //首先要判断队列是否是空
        synchronized(this) {
            if (size == 0) {
                //就要进行阻塞等待
                this.wait();
                return -9999;
            }
            int result = elems[head];
            head++;
            if (head >= elems.length) {
                head = 0;
            }
            size--;
            this.notify();
            return result;
        }

    }
}
public class Demo2 {
    public static void main(String[] args) {
        MyBlockingQueue  tt=new MyBlockingQueue(10);
        Thread t1=new Thread(()->{
            int count=0;
            while(true){
                try {
                    tt.put(count);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println("生产者: "+count);
                count++;
            }
        });
        Thread t2=new Thread(()->{
            int value;
            while(true){
                try {
                    value=tt.take();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println("消费者: "+value);
            }
        });
        t1.start();
        t2.start();
    }

}